package org.openclinic.controller;

import javax.validation.Valid;

import org.openclinic.domain.HealthInsurance;
import org.openclinic.exception.AbstractExceptionHandler;
import org.openclinic.exception.DomainException;
import org.openclinic.service.HealthInsuranceService;
import org.openclinic.to.DataTablesTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

@Controller
@SessionAttributes("healthInsurance")
public class HealthInsuranceController extends AbstractExceptionHandler {

	@Autowired
	private HealthInsuranceService healthInsuranceService;

	@ResponseBody
	@RequestMapping(value = "/insurance/delete.action", method = RequestMethod.POST)
	public boolean delete(@RequestParam long id) {
		healthInsuranceService.delete(id);
		return true;
	}
	
	@RequestMapping(value = "/insurance.do", method = RequestMethod.GET)
	public String init() {	
		return "health-insurance.view";
	}

	@RequestMapping(value = "/insurance/open.diag", method = RequestMethod.POST)
	public ModelAndView openDialog(@RequestParam Long id) {
		ModelAndView modelAndView = new ModelAndView("insurance-form.jsp");
		
		if (id == null) {
			modelAndView.addObject("healthInsurance", new HealthInsurance());
		} else {
			modelAndView.addObject("healthInsurance", healthInsuranceService.find(id));
		}
		
		return modelAndView;
	}

	@ResponseBody
	@RequestMapping(value = "/insurance/list.action", method = RequestMethod.POST)
	public DataTablesTO<HealthInsurance> list() {
		return new DataTablesTO<HealthInsurance>(healthInsuranceService.list());
	}
	
	@ResponseBody
	@RequestMapping(value = "/insurance/save.action", method = RequestMethod.POST)
	public HealthInsurance save(@Valid @ModelAttribute HealthInsurance healthInsurance, BindingResult validationResult) {
		if(!validationResult.hasErrors()) {
			healthInsuranceService.save(healthInsurance);
			return healthInsurance;
		}
		throw new DomainException(validationResult.getAllErrors());
	}
	
}
